package com.pbxadmin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SecurityController {
	private Logger log = LoggerFactory.getLogger(SecurityController.class);
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String login(HttpServletRequest req){
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String url = req.getParameter("url");
		if("admin".equals(username) && "admin".equals(password)){
			HttpSession session = req.getSession(true);
			session.setAttribute("login", "Y");
			
			if(url != null && !url.isEmpty()){
				System.out.println(url.substring(9));
				return "redirect:"+url.substring(9);
			}
			return "/sippeer/list";
		}
		log.debug(">>>> login post...{},{}",username,password);
		
		req.setAttribute("message", "username or password is wrong, please check it.");
		return "/security/login";
	}
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public ModelAndView initLogin(HttpServletRequest req,HttpServletResponse resp){
		log.debug(">>>> login get...{},{}",req.getAttribute("message"),req.getAttribute("requestURI"));
		String url = req.getParameter("url");
		if(url == null){
			url = "";
		}
		return new ModelAndView("/security/login","url",url);
	}
	
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest req){
		HttpSession session = req.getSession();
		if(session != null){
			session.removeAttribute("login");
		}
		log.debug(">>>> logout...");
		return "redirect:/";
	}
}
